package com.yrxy.thread.interview.threadlocal;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;

/**
 * @author huanglaoxie(微信:yfct-8888)
 * @className ReferenceDemo
 * @description：
 * @date 2017/7/10 17:45
 */
public class ReferenceDemo {
    public static void main(String[] args) throws InterruptedException {
        WeakReference weakReference = new WeakReference(new User("huanglaoxie",24));
//        System.gc();
        System.out.println("弱引用，手动触发GC:" + weakReference.get());

        ReferenceQueue referenceQueue1 = new ReferenceQueue();
        PhantomReference phantomReference = new PhantomReference(new User("huanglaoxie", 24), referenceQueue1);
        System.out.println("虚引用，什么也不做，获取:" + phantomReference.get());

        ReferenceQueue<User> referenceQueue = new ReferenceQueue();
        SoftReference softReference = new SoftReference(new User("huanglaoxie",24), referenceQueue);
        System.gc();
        System.out.println("软引用，手动触发GC:" + softReference.get());

        WeakHashMap<User, String> weakHashMap = new WeakHashMap();
        //强引用
        User huanglaoxie = new User("huanglaoxie", 24);
        weakHashMap.put(huanglaoxie, "huanglaoxie");
        System.out.println("有强引用的时候:map大小" + weakHashMap.size());
        //去掉强引用
        huanglaoxie = null;
        System.gc();
        Thread.sleep(1000);
        System.out.println("无强引用的时候:map大小"+weakHashMap.size());
        System.out.println("弱引用，手动触发GC:" + weakReference.get());


        //手动触发GC
//        System.gc();
//        Thread.sleep(1000);
//        System.out.println("手动触发GC:" + softReference.get());
//        System.out.println("手动触发的队列:" + referenceQueue.poll());
//        //通过堆内存不足触发GC
//        makeHeapNotEnough();
//        System.out.println("通过堆内存不足触发GC:" + softReference.get());
//        System.out.println("通过堆内存不足触发GC:" + referenceQueue.poll());
    }

//    private static void makeHeapNotEnough() {
//        SoftReference softReference = new SoftReference(new byte[1024*1024*5]);
//        byte[] bytes = new byte[1024*1024*5];
//    }
}
